
import { _decorator, Component, Node, ProgressBar, Label, Prefab, AudioClip, game, Scene, SceneAsset, find, labelAssembler, EventTouch, Asset, assetManager, AssetManager, isValid } from 'cc';
import { AppConst, BundlesConst, FormConst } from '../ccc3-framework-core/const/Const';
import { ListType } from '../ccc3-framework-core/framework/extends/ListView/List';
import { audioManager } from '../ccc3-framework-core/framework/modules/audioManager';
import { BaseObject } from '../ccc3-framework-core/framework/modules/baseObject';
import { BundleMgr } from '../ccc3-framework-core/framework/modules/bundleMgr';
import dataUtil from '../ccc3-framework-core/framework/modules/dataUtil';
import { entityUtil } from '../ccc3-framework-core/framework/modules/entityUtil';
import eventUtil from '../ccc3-framework-core/framework/modules/eventUtil';
import { httpUtil } from '../ccc3-framework-core/framework/modules/httpUtil';
import { memoryConfig } from '../ccc3-framework-core/framework/modules/memoryConfig';
import { poolManager } from '../ccc3-framework-core/framework/modules/poolManager';
import { resourceUtil } from '../ccc3-framework-core/framework/modules/resourceUtil';
import { SheetManager } from '../ccc3-framework-core/framework/modules/sheetManager';
import { uiManager } from '../ccc3-framework-core/framework/modules/uiManager';
import { UiForm } from '../ccc3-framework-core/framework/ui/uiForm';
import { gameState } from '../ccc3-framework-core/gameState';
import { shareInfo } from '../ccc3-framework-core/model/shareInfo';
import { platformConf } from '../ccc3-framework-core/platform/platformConf';
import { platformUtil } from '../ccc3-framework-core/platform/platformUtil';
import Common from '../ccc3-framework-core/utils/Common';
import { Debug } from '../ccc3-framework-core/utils/Debug';
import { ConfigData } from '../sheets/vo/ConfigData';
import { SplashCfg } from '../sheets/vo/SplashCfg';
import { BundlesDefine, CategoryDefine, entityDefine, eventDefine, formDefine, guideStep, pathDefine } from './CustomDefine';
import { dialogForm } from './home/dialogForm';
import TaskWeb from '../3rd/Guyu/Scripts/[业务]/广告任务/Controller/TaskWeb';
import { UIManager } from '../3rd/Guyu/Scripts/[框架]/通用UI/UIManager';
import TaskResMgr from '../3rd/Guyu/Scripts/[业务]/广告任务/Model/TaskResMgr';
import { TaskDefine } from '../3rd/Guyu/Scripts/[业务]/广告任务/Model/TaskDefine';

const { ccclass, property } = _decorator;
export class loadModel {
    public isResources: boolean;
    public bundleOrPath: string;
    public loadType: any;
    public isDir: boolean;
    public isScene: boolean;
    public dirOrName: string;
    public memo: string
}
@ccclass('loadingScene')
export class loadingScene extends BaseObject {

    @property(ProgressBar)
    progressBar: ProgressBar = null!;

    @property(Label)
    txtVersion: Label = null!;

    @property(Node)
    splash: Node = null!;

    @property(Label)
    txtSplash: Label = null;

    @property(Label)
    txtLoading: Label = null;

    @property(Label)
    txt版号: Label = null;

    @property(Node)
    loadingNode: Node = null!;

    @property(Label)
    txtProgress: Label = null!;

    private openScene: boolean = false;
    private test3D: boolean = true;
    private tdScene: string = "level1";
    private testLevel: number = 1001;
    private firstScene: string = "main";
    start() {
        this.setAppInfo();
        TaskWeb.getTaskConfig();
        game.addPersistRootNode(this.node);
        this.loadingNode.active = true;
        this.splash.active = false;
        eventUtil.on(eventDefine.SHOW_LOADING, this, (e) => {
            if (typeof e == "boolean") {
                this.showSplash(!!e)
            }
            else {
                this.showSplash(e.show, e.callback);
            }
        });

        eventUtil.on(eventDefine.SHOW_DIALOG, this, this.onShowDialog);
        UIManager.getInstance().init().then(() => {
            TaskResMgr.init();
        });
    }

    private setAppInfo() {
        this.txt版号.string = "";
        if (!window["AppInfoGlobal"]) {
            Guyu.Log.warn("没有AppInfoGlobal");
            return;
        }
        let appInfo = window["AppInfoGlobal"] as TaskDefine.IAppInfo;
        if (!appInfo) {
            Guyu.Log.warn("没有AppInfoGlobal2");
            return;
        }
        let str = ``;
        if (appInfo.softInfo) {
            str = `${appInfo.softInfo}`;
        }
        if (appInfo.companyName) {
            str += `\r\n${appInfo.companyName}`;
        }
        this.txt版号.string = str;
        Guyu.Log.warn("txt版号=", str);
    }

    private changeMemo() {
        let all = SplashCfg.getAll();
        let memo = all[Common.randomNumBoth(0, all.length - 1)].memo;
        this.txtSplash.string = memo;
        this.txtLoading.string = memo;
    }

    private prevShowTime: number = 0;
    private showSplash(show: boolean, callback?: () => void) {
        let showSplash: boolean = show;
        if (showSplash) {
            this.prevShowTime = Date.now();
            this.splash.active = true;
            this.splash.setSiblingIndex(this.splash.parent.children.length - 1);
            this.changeMemo();
        }
        else {
            let curShowTime: number = Date.now();
            let timeDiff: number = curShowTime - this.prevShowTime;
            let delayTime: number = 1500;
            if (timeDiff > delayTime) {
                this.splash.active = false;
                if (callback)
                    callback();
            }
            else {
                let t = (delayTime - timeDiff) / 1000;
                this.scheduleOnce(() => {
                    this.splash.active = false;
                    if (callback)
                        callback();
                }, t)
            }
        }

    }



    onLoad() {
        httpUtil.getAllConfig((res: any) => {
            Debug.log('getAllConfig', res);
            memoryConfig.instance.addObject(res)
            let zs = (window as any)["zs"];
            if (zs) {
                let zhiseSdK = zs.sdk;
                zhiseSdK.loadCfg((zhiseResult: any) => {
                    Debug.log('加载参数', zhiseResult)
                    memoryConfig.instance.addObject(zhiseResult)
                    memoryConfig.instance.setKey('version', zhiseResult.zs_version);
                    this.resetMemory(zhiseResult);

                    this.initShareInfo();
                    this.loadRes();
                })
            }
            else {
                this.initShareInfo();
                this.loadRes();
            }
        })
    }

    private initShareInfo() {
        let share_info: Array<shareInfo> = [
            { img: "", title: "" }
        ];
        let share_info2 = memoryConfig.instance.getKey("share_info", share_info);
        platformUtil.currentPlatform.initShare(share_info);
    }

    private resetMemory(result) {
        if (platformConf.currentApp == AppConst.VIVO) {
            if (result.zs_version != platformConf.config.version) {
                memoryConfig.instance.setKey('zs_native_click_switch', 0);
                memoryConfig.instance.setKey('zs_native_limit', 0);
                memoryConfig.instance.setKey('zs_native_show_scene', 0);
                memoryConfig.instance.setKey('zs_native_touch_switch', 0);
                memoryConfig.instance.setKey('zs_native_next_limit', 0);
            }
        }
        else if (platformConf.currentApp == AppConst.WX) {
            memoryConfig.instance.setKey('zs_native_click_switch', 0);
            memoryConfig.instance.setKey('zs_native_limit', 0);
            memoryConfig.instance.setKey('zs_native_show_scene', 0);
            memoryConfig.instance.setKey('zs_native_touch_switch', 0);
            memoryConfig.instance.setKey('zs_native_next_limit', 0);
        }
    }


    private progressIndex: number = 0;
    private progressValue: number = 0;
    /**
     * 进入小镇资源加载
     */
    private loadQueue1: Array<loadModel> = [
        { isResources: false, bundleOrPath: BundlesConst.images, loadType: AssetManager.Bundle, isScene: false, isDir: false, dirOrName: "", memo: "游戏初始化..." },
        // { isResources: false, bundleOrPath: BundlesConst.common, loadType: AssetManager.Bundle, isScene: false, isDir: false, dirOrName: "", memo: "角色初始化..." },
        { isResources: true, bundleOrPath: "", loadType: AudioClip, isDir: true, isScene: false, dirOrName: "sound", memo: "音乐加载中..." },
        { isResources: true, bundleOrPath: "", loadType: Prefab, isDir: true, isScene: false, dirOrName: "prefab", memo: "资源加载中..." },
        { isResources: false, bundleOrPath: BundlesDefine.main, loadType: Prefab, isScene: true, isDir: true, dirOrName: this.firstScene, memo: "准备进入游戏..." },
    ];


    private currentQueue: Array<loadModel> = []
    private loadNext() {
        this.progressIndex++;
        this.progressValue = 0;
        let item = this.currentQueue[this.progressIndex];
        this.txtLoading.string = item.memo;
        if (item) {
            if (item.isResources) {
                if (item.isDir) {
                    if (item.loadType == Prefab) {
                        resourceUtil.loadAssetDir(item.dirOrName, Prefab, (percent: number) => {
                            this.setProgressValue(percent);
                        }, (err, res: Array<Prefab>) => {
                            if (err) {
                                this.progressValue = 1;
                                this.loadNext();
                                return;
                            }
                            poolManager.addPrefabs(res);
                            this.progressValue = 1;
                            this.loadNext();
                        });
                    }
                    else if (item.loadType == AudioClip) {
                        resourceUtil.loadAssetDir(item.dirOrName, AudioClip, (percent: number) => {
                            this.setProgressValue(percent);
                        }, (err, res: Array<AudioClip>) => {
                            if (err) {
                                this.progressValue = 1;
                                this.loadNext();
                                return;
                            }
                            res.forEach(item => {
                                audioManager.addAudio(item);
                            })
                            this.progressValue = 1;
                            this.loadNext();
                        });
                    }
                }
            }
            else {
                if (item.isDir) {
                    if (item.isScene) {
                        resourceUtil.preloadScene(item.dirOrName, (completedCount: number, totalCount: number, item: any) => {
                            var percent = completedCount / totalCount;
                            if (this.currentQueue.length - 1 == this.progressIndex && percent > 0.99) {
                                percent = 0.99;
                            }
                            this.setProgressValue(Math.floor(percent * 100));
                        }, (error: Error | null) => {
                            if (this.test3D)
                                memoryConfig.instance.level = this.testLevel;
                            if (this.currentQueue.length - 1 == this.progressIndex) {
                                this.progressValue = 0.99;
                                this.execScene();
                            }
                            else {
                                this.progressValue = 1;
                                this.loadNext();
                            }
                        }, item.bundleOrPath);
                    }
                    else if (item.loadType == Prefab) {
                        resourceUtil.loadBundleDir(item.bundleOrPath, item.loadType, item.dirOrName, (percent) => {
                            this.setProgressValue(percent);
                        }, (err, resList) => {
                            if (err) {
                                this.progressValue = 1;
                                this.loadNext();
                                return;
                            }
                            poolManager.addPrefabs(resList);
                            this.progressValue = 1;
                            this.loadNext();
                        });
                    }

                }
                else if (item.loadType == AssetManager.Bundle) {
                    resourceUtil.loadBundle(item.bundleOrPath, () => {
                        this.setProgressValue(1);
                        this.loadNext();
                    }, (percent) => {
                        this.setProgressValue(percent);
                        Debug.log("加载bundle ", item.bundleOrPath)
                    });
                }
            }
        }
    }


    private setProgressValue(percent: number) {
        if (percent > this.progressValue) {
            this.progressValue = isNaN(percent) ? 0 : percent;
            this.txtProgress.string = "" + (this.progressValue.toFixed(0)) + "%";
            this.progressBar.progress = this.progressValue / 100;
        }
    }

    private loadRes() {
        let cfg = `data/cfg`;
        this.setProgressValue(0);
        if (Common.isHttp(platformConf.config.excelUrl)) {
            cfg = `${platformConf.config.excelUrl}${cfg}.json?r=${Math.random()}`;
        }
        Debug.log('load cfg json ', cfg)
        SheetManager.loadDB(`${cfg}`, () => {
            ConfigData.init();
            this.changeMemo();
            this.progressIndex = -1;
            // this.currentQuene = this.loadQuene2;
            // if (dataUtil.isUnlockByDetailId(this.testLevel)) {
            this.currentQueue = this.loadQueue1;
            // }
            // this.currentQuene = this.loadQuene1;
            this.loadNext();
        });
    }

    private onShowDialog(e: { msg: string, step: guideStep, hide: boolean }) {
        // if (e.hide == true) {
        //     entityUtil.hideAllEntity(formDefine.dialogForm);
        //     this.dialogNode = null;
        // }
        // else {
        //     if (this.dialogNode instanceof Node) {
        //         entityUtil.hideEntity(this.dialogNode);
        //         this.dialogNode = null;
        //     }
        //     this.showDialog(e.msg, e.step);
        // }
    }
    private dialogNode: Node;
    private showDialog(msg: string, step?: guideStep) {
        // if (this.dialogNode == null) {
        //     this.dialogNode = {} as any;
        //     entityUtil.showEntity(pathDefine.form_townform + formDefine.dialogForm, this.node, (dialog) => {
        //         this.dialogNode = dialog;
        //         dialog.getComponent(dialogForm).init(msg, step);
        //     }, BundlesConst.form)
        // }
        // else if (this.dialogNode instanceof Node) {
        //     this.dialogNode.getComponent(dialogForm).init(msg, step);
        // }

        // uiManager.pushUIForm(pathDefine.form_townform + formDefine.dialogForm, (node) => {
        //     node.getComponent(dialogForm).init(msg);
        // }, BundlesConst.form);
    }

    private execScene() {
        Debug.log('loading end');
        if (this.openScene) return;
        this.openScene = true;
        // if (dataUtil.isUnlockByDetailId(this.testLevel)) {
        // uiManager.pushUIForm(`${pathDefine.form_townform}${formDefine.homeForm}`, (formOwner) => {
        //     formOwner.active = false;
        //     eventUtil.dispatchEvent(eventDefine.LEVEL_CHANGED, null);
        //     eventUtil.dispatchEvent(eventDefine.COIN_CHANGED, null);

        // }, BundlesDefine.main);
        resourceUtil.loadScene(this.firstScene, () => {
            this.loadingNode.active = false;
            // formOwner.active = true;
            this.progressValue = 1;
        }, BundlesDefine.main);
        // }
        // else {
        //     resourceUtil.loadScene(this.tdScene, () => {
        //         this.loadingNode.active = false;
        //         this.progressValue = 1;
        //     }, BundlesConst.tdPrefabs);
        // }

    }

    update(dt: number) {

        if (this.splash.active)
            this.splash.setSiblingIndex(this.splash.parent.children.length - 1);

        if (this.dialogNode instanceof Node) {
            this.dialogNode.active = !this.splash.active;
            // let h = uiManager.getUIForm(formDefine.homeForm);
            // if (h && isValid(h))
            //     this.dialogNode.parent = h;
            // else
            this.dialogNode.parent = this.node;
            this.dialogNode.setSiblingIndex(this.dialogNode.parent.children.length - 1);
        }

        let minute_fatigue_num = memoryConfig.instance.getIntKey("minute_fatigue_num", 1);
        let minute_fatigue = memoryConfig.instance.getIntKey("minute_fatigue", 10);
        let total_fatigue_time = memoryConfig.instance.getFloatKey("total_fatigue_time", 0);
        total_fatigue_time += dt;
        memoryConfig.instance.setKey("total_fatigue_time", total_fatigue_time);

        if (total_fatigue_time >= minute_fatigue * 60) {
            total_fatigue_time = 0;
            memoryConfig.instance.setKey("total_fatigue_time", total_fatigue_time);
            let local_fatigue_num = dataUtil.getUnlockNumByDetailId(1, CategoryDefine.FATIGUE);
            let addNum = 0;
            if (local_fatigue_num >= 0) {
                addNum = local_fatigue_num + minute_fatigue_num;
                dataUtil.addUnlock(1, CategoryDefine.FATIGUE, addNum, 0);
            }
            else {
                dataUtil.setUnlock(1, CategoryDefine.FATIGUE, minute_fatigue_num, 0);
            }

            eventUtil.dispatchEvent(eventDefine.FATIGUE_NUM_CHANGED, null);
        }

    }
}

/**
 * [1] Class member could be defined like this.
 * [2] Use `property` decorator if your want the member to be serializable.
 * [3] Your initialization goes here.
 * [4] Your update function goes here.
 *
 * Learn more about scripting: https://docs.cocos.com/creator/3.0/manual/en/scripting/
 * Learn more about CCClass: https://docs.cocos.com/creator/3.0/manual/en/scripting/ccclass.html
 * Learn more about life-cycle callbacks: https://docs.cocos.com/creator/3.0/manual/en/scripting/life-cycle-callbacks.html
 */
